package com.joinway.mobile.service;

import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional

import com.joinway.framework.admin.bean.domain.UserProfile
import com.joinway.framework.core.repository.SystemConfigRepository;
import com.joinway.framework.data.jdbc.repository.TableRepository
import com.joinway.framework.ecshop.bean.domain.User
import com.joinway.framework.ecshop.utils.EcShopUtils
import com.joinway.mobile.bean.view.LoginView
import com.joinway.mobile.bean.view.VersionView
import com.joinway.mobile.exception.MobileErrorConstants
import com.joinway.mobile.exception.MobileException

@Service
public class MobileService {

	private final static Logger log = LoggerFactory.getLogger(MobileService.class);
	
	@Autowired SystemConfigRepository systemRepository;
	
	@Autowired EcShopService ecshopService;
	
	@Autowired TableRepository repository
	
	@Transactional(rollbackFor=Throwable.class)
	public LoginView register(String name, String password, String cellPhone, String cellPhoneType) throws Exception {
//		log.info("user name is $name")
		User user = ecshopService.findUser(name)
		if(user != null){
			throw new MobileException(MobileErrorConstants.USER_REGISTERED);
		}
		
		Date today = Calendar.getInstance().getTime();
		
		/*
		 * 保存用户注册信息
		 */
		String salt = EcShopUtils.createSalt();
		user = new User();
		user.userName = name.toLowerCase()
		user.password = EcShopUtils.encrypt(password, salt);
		user.ecSalt = salt
		user.mobilePhone = cellPhone
		user.visitCount = 1
		user.lastLogin = today.getTime() / 1000
		user.regTime = today.getTime() / 1000
		repository.save(user, "login_user");
		
		updateUserProfile(user.userId, cellPhoneType)
		
		LoginView view = new LoginView();
		
		view.setUserId(String.valueOf(user.userId));
		
		return view;
	}
	
	@Transactional(rollbackFor=Throwable.class)
	public LoginView login(String name, String password, String cellPhoneType) throws Exception {
		User user = ecshopService.findUser(name)
		if(user == null){
			throw new MobileException(MobileErrorConstants.INVALID_NAME_OR_PWD);
		}
		
		user = ecshopService.findUser(name, password)
		if(user == null){
			throw new MobileException(MobileErrorConstants.INVALID_NAME_OR_PWD);
		}
		
		/*
		 * 更新用户登录信息
		 */
		Date today = Calendar.getInstance().getTime();
		
		user.visitCount++
		user.lastLogin = today.getTime() / 1000
		repository.save(user, "login_user")
		
		updateUserProfile(user.userId, cellPhoneType)
		
		LoginView view = new LoginView();
		
		view.setUserId(String.valueOf(user.userId));
		
		return view;
	}
	
	public VersionView getLatestVersion() throws Exception {
		VersionView view = new VersionView();
		view.setVersion(systemRepository.getStringValue(SystemConfigRepository.ClientVersion));
		view.setUrl(systemRepository.getStringValue(SystemConfigRepository.ClientDownlaodUrl));
		
		return view;
	}
	
	@Transactional(rollbackFor=Throwable.class)
	public void changePassword(String name, String oldPassword, String newPassword) throws Exception {
		User user = ecshopService.findUser(name, oldPassword)
		if(user == null){
			throw new MobileException(MobileErrorConstants.INVALID_NAME_OR_PWD);
		}
		
		user.setPassword(EcShopUtils.encrypt(newPassword, user.ecSalt));
		repository.save(user, "login_user");
	}
	
	protected void updateUserProfile(int userId, String cellPhoneType){
		List domains = repository.find(UserProfile, "select * from user_profile where user_id = ?", userId)
		UserProfile up = domains && domains.size() > 0 ? domains.get(0) : new UserProfile()
		up.userId = userId
		up.cellPhoneType = cellPhoneType
		repository.save(up)
	}
}

